package registerCenter;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;


import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class StubComplieHandler implements Runnable {

	private String serviceURI;
	
	String parentString;

	public StubComplieHandler(String serviceURI) {
		super();
		this.serviceURI = serviceURI;
		parentString = new File("").getAbsolutePath();
		parentString = new File(parentString).getParent();
		parentString = parentString
				+ "/server/default/deploy/ESB-SOA-Adapter.war/";
	}

	@Override
	public void run() {

		serviceURI = serviceURI.replaceAll("://", "/");
		serviceURI = serviceURI.replaceAll("\\\\", "/");
		serviceURI = serviceURI.replaceAll("\\.", "/");
		while (serviceURI.startsWith("/")) {
			serviceURI = serviceURI.substring(0);
		}
		while (serviceURI.endsWith("/")) {
			serviceURI = serviceURI.substring(0, serviceURI.length() - 1);
		}

		
		String sourcepath = parentString + "src/service/" + serviceURI;
		String despath = parentString + "WEB-INF/classes/service/" + serviceURI;
		File sFile = new File(sourcepath);
		File dFile = new File(despath);

		if (sFile.exists()) {

			File[] files = sFile.listFiles(new MyFilter());

			if (files.length > 0) {
				if (dFile.exists()) {
					if (dFile.listFiles().length == 0) {
						compileStubs(sourcepath, files);
					}
				} else {
					compileStubs(sourcepath, files);
				}
			}
		}
	}

	private void compileStubs(String sourcepath, File[] files) {
		System.out.println("compiling stubs......");
		ArrayList<String> options = new ArrayList<String>();
		options.add("-sourcepath");
		options.add(sourcepath);
		options.add("-d");
		options.add(parentString+"WEB-INF/classes");
		options.add("-classpath");
		options.add(parentString+"WEB-INF/lib/axis.jar");
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(
				null, null, null);

		Iterable<? extends JavaFileObject> compilationUnits = fileManager
				.getJavaFileObjectsFromFiles(Arrays.asList(files));
		boolean result = compiler.getTask(null, fileManager, null, options, null,
				compilationUnits).call();
		
		if(result){
			System.out.println("compiling finished");
		}else{
			System.out.println("compiling failed");
		}

	}
}

class MyFilter implements FilenameFilter {

	public boolean accept(File dir, String name) {
		return name.endsWith(".java");
	}

}
